import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import DTO.userinfomation;
@WebServlet("/upload_servlet")
@MultipartConfig(location = "C:\\Users\\zhu\\IdeaProjects\\experiment_15\\src\\main\\webapp\\photo")// location改为本地的绝对路径
public class upload_servlet extends HttpServlet{
    private static final String URL = "jdbc:h2:~/jpa-demo-db;MODE=MYSQL;DB_CLOSE_DELAY=-1";
    private static final String NAME = "sa";
    private static final String PASSWORD = "sa";
    private static final EntityManagerFactory entityManagerFactory;
    private static final String PERSISTENCE_UNIT_NAME = "MyJPADemoPU";

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    }

    private EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }

    public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{

        Part part = req.getPart("userhead");
        if(part == null ) {
            resp.setContentType("text/html;charset=UTF-8");
            resp.getWriter().println("您没有上传文件!");
            resp.getWriter().println("<br>");
            resp.getWriter().println("<input type = submit value = 点此重新上传 onclick = location='user.jsp'>");
        }
        ArrayList<userinfomation> user_array = new ArrayList<userinfomation> ();
        Map<String,String> user =(Map<String ,String>)req.getSession().getAttribute("USER");
        String username = user.get("username");
        String filename =  username.concat(part.getSubmittedFileName());

        part.write(filename);
        try {
            String sql_1 = "UPDATE USERINFOMATION SET IMG = " +"'" + filename + "'" + " WHERE USERNAME = " + "'"+ username + "'";
            Connection conn = DriverManager.getConnection(URL, NAME, PASSWORD);
            Statement stmt = conn.createStatement();
            stmt.executeUpdate(sql_1);
        }catch (SQLException e) {
            e.printStackTrace();
            resp.sendRedirect("error.html");
        }
        user.put("img",filename);
        HttpSession session = req.getSession(true);
        Map<String,String >map = new HashMap<>();
        map.put("username",user.get("username"));
        map.put("phone",user.get("phone"));
        map.put("password",user.get("password"));
        map.put("img",user.get("img"));
        session.setAttribute("USER",map);
        resp.sendRedirect("user.jsp");

    }
}
